#!/bin/bash
set -e
BASE="$(cd "$(dirname "$0")/.."; pwd)"
PGDATA="$BASE/pgsql/data"
PGBIN="$BASE/pgsql/bin"
export PATH=$PGBIN:$PATH

# 1️⃣ 首次初始化
[[ -f "$PGDATA/PG_VERSION" ]] || $PGBIN/initdb -D "$PGDATA" --encoding=UTF8 --locale=C

# 2️⃣ 启动
$PGBIN/pg_ctl -D "$PGDATA" -l "$PGDATA/pg.log" start

# 3️⃣ 建库 + 导入 schema/seed
$PGBIN/psql -d postgres -c "CREATE DATABASE myapp;"
$PGBIN/psql -d myapp -f "$BASE/pgsql/init.sql"